package com.jy.app.lib.view.custom;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewTreeObserver;

import com.jy.app.lib.application.BaseApplication;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 15014 on 2017/4/26.
 */

public class ShapeChangeLoadingView extends View {
    private int circularDiameter = 25;  //圆直径
    private  int VIEW_REFRESH_TIME = 20; //界面刷新时间单位毫秒

    private int maxMoveDistance = 0;  //最大可移动距离
    private int currentMoveDistance = 0;  //当前移动距离

    private int triangleLength;  // 三角形边长
    private int squareLength;  //正方形边长

    private float angle = 0f; //旋转角度
    private int movingSpeed = 12; //移动速度 越大则越慢

    private int circularColor = Color.rgb(113,140,225),triangleColor = Color.rgb(204,0,204),squareColor = Color.rgb(234,77,57),shadowColor = Color.rgb(155,155,155); //声明图形颜色

    private int VIEW_WIDE,VIEW_HEIGHT;// 声明控件宽高
    private Paint paint;

    private List<Integer> position = new ArrayList<>(); // 移动轨迹

    private int graphicalpos = 1;    //当前显示图形 1-圆形 2-三角形 3-四边形

    private boolean isUpMove = true; //当前是否在向上移动

    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            invalidate();
        }
    };
    public ShapeChangeLoadingView(Context context) {
        super(context);
    }

    public ShapeChangeLoadingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init(){
        try {
        int colorId = getResources().getIdentifier("title_color",
                "color", BaseApplication.appContext.getPackageName());
        circularColor = getResources().getColor(colorId);
        }catch (Exception e){

        }
        circularDiameter = dip2px(circularDiameter);
        triangleLength =((int)(circularDiameter/Math.sin(Math.PI*60/180))/5*4);
        squareLength = circularDiameter/5*4;
        getCoreLocation();
        initPaint();
    }

    private void initPaint(){
        paint = new Paint();
        paint.setAntiAlias(true); //打开抗锯齿
        paint.setDither(true);  //设置是否抖动
    }

    /**
     *设置图形大小
     * @param dipSize 图形大小
     * */
    public void setShapeSize(int dipSize){
        if (dipSize<=0)
            return;
        circularDiameter = dipSize;
        circularDiameter = dip2px(circularDiameter);
        triangleLength =((int)(circularDiameter/Math.sin(Math.PI*60/180))/5*4);
        squareLength = circularDiameter/5*4;
    }

    /**
     * 设置移动速度 原大移动速度则原小
     * @param movingSpeed 移动速度
     * */
    public void setMovingSpeed(int movingSpeed){
        this.movingSpeed = movingSpeed;
    }

    /**
     * 设置圆形图片颜色
     * @param circularColor 颜色
     * */
    public void setCircularColor(int circularColor){
        this.circularColor = circularColor;
    }

    /**
     * 设置三角形颜色
     * @param triangleColor 颜色
     * */
    public void setTriangleColor(int triangleColor){
        this.triangleColor = triangleColor;
    }

    /**
     * 设置正方形颜色
     * @param squareColor 颜色
     * */
    public void setSquareColor(int squareColor){
        this.squareColor = squareColor;
    }

    /**
     * 设置阴影颜色
     * @param shadowColor 颜色
     * */
    public void setShadowColor(int shadowColor){
        this.shadowColor = squareColor;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //加载不同图片
        switch (graphicalpos){
            case 1: circular(canvas);
                break;
            case 2: triangle(canvas);
                break;
            case 3: square(canvas);
                break;
        }
        //绘制阴影
        shadow(canvas);
        super.onDraw(canvas);
        handler.postDelayed(runnable,VIEW_REFRESH_TIME);   //通知刷新界面
    }

    /**
     * 底部阴影
     * */
    private void shadow(Canvas canvas){
        paint.setColor(shadowColor);  //修改画笔颜色
        RectF oval=new RectF();
        oval.top=VIEW_HEIGHT-dip2px(6);
        oval.bottom = VIEW_HEIGHT;
        oval.left = (VIEW_WIDE-20 -currentMoveDistance/4)/2;;
        oval.right = oval.left+20+currentMoveDistance/4;
        canvas.drawArc(oval,0 ,360 , false, paint);
    }

    /**
     *画圆
     * */
    private void circular(Canvas canvas){
        paint.setColor(circularColor);
        RectF oval=new RectF();
        setMoveDistance();
        oval.top=(VIEW_HEIGHT-circularDiameter- currentMoveDistance )/5*4 ;
        oval.left = (VIEW_WIDE-circularDiameter)/2;;
        oval.right = oval.left+circularDiameter;
        oval.bottom = oval.top+circularDiameter;
        canvas.drawArc(oval,0 ,360 , false, paint);
    }

    /**
     * 三角形
     * */
    private void triangle(Canvas canvas){
        paint.setColor(triangleColor);
        Path path = new Path();
        setMoveDistance();
        angle = 255*(currentMoveDistance/(float)maxMoveDistance);
        int Y = (VIEW_HEIGHT-circularDiameter - currentMoveDistance)/5*4+circularDiameter;
        Float[] f1 = calculationCoordinate((VIEW_WIDE-triangleLength)/2,Y,VIEW_WIDE/2,Y-(triangleLength/2),angle);
        path.moveTo(f1[0],f1[1]);
        Float[] f2 = calculationCoordinate((VIEW_WIDE-triangleLength)/2+triangleLength,Y,VIEW_WIDE/2,Y-(triangleLength/2),angle);
        path.lineTo(f2[0],f2[1]);
        Float[] f3 = calculationCoordinate(VIEW_WIDE/2,Y-triangleLength,VIEW_WIDE/2,Y-(triangleLength/2),angle);
        path.lineTo(f3[0],f3[1]);
        path.close();
        canvas.drawPath(path,paint);
    }

    /**
     * 正方形
     * */
    private void square(Canvas canvas){
        paint.setColor(squareColor);
        Path path = new Path();
        setMoveDistance();
        angle = -285*(currentMoveDistance/(float)maxMoveDistance);
        int Y = (VIEW_HEIGHT-circularDiameter - currentMoveDistance)/5*4+circularDiameter;
        Float[] f1 = calculationCoordinate((VIEW_WIDE-squareLength)/2,Y,VIEW_WIDE/2,Y-(squareLength/2),angle);
        path.moveTo(f1[0],f1[1]);
        Float[] f2 = calculationCoordinate((VIEW_WIDE-squareLength)/2+squareLength,Y,VIEW_WIDE/2,Y-(squareLength/2),angle);
        path.lineTo(f2[0],f2[1]);
        Float[] f3 = calculationCoordinate((VIEW_WIDE-squareLength)/2+squareLength,Y-squareLength,VIEW_WIDE/2,Y-(squareLength/2),angle);
        path.lineTo(f3[0],f3[1]);
        Float[] f4 = calculationCoordinate((VIEW_WIDE-squareLength)/2,Y-squareLength,VIEW_WIDE/2,Y-(squareLength/2),angle);
        path.lineTo(f4[0],f4[1]);
        path.close();
        canvas.drawPath(path,paint);
    }

    /**
     * 计算上移距离
     * */
    private void setMoveDistance(){
        if (isUpMove){
            position.add((maxMoveDistance-currentMoveDistance)/movingSpeed + 3);
            currentMoveDistance+= position.get(position.size()-1);
            if (currentMoveDistance >= maxMoveDistance){
                angle = 0f;
                isUpMove = false;
            }
        }else{
            currentMoveDistance-= position.get(position.size()-1);
            position.remove(position.size()-1);
            if (position.size()==0) {
                currentMoveDistance = 0;
                isUpMove = true;
                graphicalpos++;
                if (graphicalpos == 4){
                    graphicalpos = 1;
                }
            }
        }
    }

    /**
     * 获取控件宽高
     * */
    private void getCoreLocation(){
        ViewTreeObserver vto = getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                getViewTreeObserver().removeOnPreDrawListener(this);
                VIEW_HEIGHT = getMeasuredHeight();
                VIEW_WIDE = getMeasuredWidth();
                maxMoveDistance = VIEW_HEIGHT/7*4;
                return true;
            }
        });
    }

    /**
     * 将dip转化为px
     * @param dipValue dip值
     * */
    private int dip2px(float dipValue){
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int)(dipValue * scale + 0.5f);
    }
    /**
     * 通过已知坐标后旋转中心坐标以及角度计算旋转后坐标
     * */
    private Float[] calculationCoordinate(float x1,float y1,float x0,float y0,float angle){
        angle =new Float(Math.toRadians(angle));
        float x2=new Float((x1-x0)*Math.cos(angle) +(y1-y0)*Math.sin(angle)+x0);
        float y2=new Float(-(x1-x0)*Math.sin(angle) + (y1-y0)*Math.cos(angle)+y0);
        return new Float[]{x2,y2};
    }
}
